package cn.org.theo.service.impl;

import cn.org.theo.mapper.*;
import cn.org.theo.pojo.*;
import cn.org.theo.qo.OrderListQo;
import cn.org.theo.qo.SubscribeFrontQo;
import cn.org.theo.qo.SubscribeQo;
import cn.org.theo.service.OrderService;
import cn.org.theo.utils.DateUtil;
import cn.org.theo.vo.*;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * project name: IntelliJ IDEA
 * Date: 2022/8/26 11:31
 *
 * @PackageName: cn.org.theo.service.impl
 * @ClassName: OrderServiceImpl
 * @Author: Theo
 * @Version:
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private SubscribeMapper subscribeMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private ConsultantMapper consultantMapper;
    @Autowired
    private ConsultantFieldMapper consultantFieldMapper;
    @Autowired
    private ConfigureMapper  configureMapper;
    @Autowired
    private AccountMoneyMapper  accountMoneyMapper;


    @Override
    public Result getOrderStatusList() {

        List<OrderStatus> list =  orderStatusMapper.query();

        return new Result(0,"数据获取成功", list);

    }

    @Override
    public Result getListForPage(SubscribeQo subscribeQo, int pageNo) {
        System.out.println(subscribeQo);
        Map<String,Object> map = new HashMap<>();
        //通过manager的name获取manager_id，放入map
        Manager manager = new Manager();
        manager.setUsername(subscribeQo.getConsName());
        Manager query = managerMapper.query(manager);
        map.put("managerId",query.getId());

        //将查询条件放入map，3个
        map.put("subTime",subscribeQo.getSubTime());
        map.put("answerTime",subscribeQo.getAnswerTime());
        map.put("subStatus",subscribeQo.getSubStatus());

        map.put("limit",(pageNo - 1) * 5);
        map.put("offset",5);

        List<SubscribeVo> subscribeVos = subscribeMapper.queryForConditionByPage(map);
        Page<SubscribeVo> page = new Page();
        page.setPageNo(pageNo);
        page.setLimit((pageNo - 1) * 5);
        page.setOffset(5);
        page.setCondition(true);
        page.setList(subscribeVos);
        subscribeQo.setManagerId(query.getId());
        page.setTotalCount(subscribeMapper.queryTotalCount(map));
        System.out.println(page.getTotalCount());
        int totalCount = page.getTotalCount();
        page.setTotalPageCount(totalCount % 5 == 0 ? totalCount / 5 : totalCount / 5 + 1);
        if (page.getTotalPageCount() == 0) {
            page.setCurrentPage(0);
        }
        return Result.updateResp(1,"数据获取成功","数据获取失败",page);
    }

    @Override
    public Result createOrder(SubscribeFrontQo subscribeFrontQo) {
        Subscribe subscribe = new Subscribe();
        //查询uid，managerId，fieldId,
        User user = new User();
        user.setUsername(subscribeFrontQo.getUsername());
        User query = userMapper.query(user);
        subscribe.setUId(query.getId());
        //获取咨询师的后台管理id
        ConsultantVo consultant = new ConsultantVo();
        consultant.setId(subscribeFrontQo.getConsId());
        Manager manager = consultantMapper.query(consultant);
        Manager query1 = managerMapper.query(manager);
        subscribe.setManagerId(query1.getId());

        subscribe.setSubStatus(1);
        subscribe.setQuestionInfo(subscribeFrontQo.getQuestion());
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = sdf.format(date);
        subscribe.setSubTime(format);
        subscribe.setAnswer("");
        subscribe.setSubId(System.currentTimeMillis() + "");
        subscribe.setAnswer("");
        ArrayList<String> objects = new ArrayList<>();
        objects.add(subscribeFrontQo.getFieldName());
        List<Field> fields = fieldMapper.queryId(objects);
        subscribe.setFieldId(fields.get(0).getId());
        int i = subscribeMapper.insert(subscribe);
        System.out.println(subscribe.getId());
        Subscribe queryOne = subscribeMapper.queryOne(subscribe);
        String subId = queryOne.getSubId();
        //插入评价表
        int i1 = evaluateMapper.insert(subId);
        //用户扣余额
        //获取咨询师费用
        Consultant consultant1 = consultantMapper.query5(subscribeFrontQo.getConsId());
        System.out.println(consultant1);
        Integer servicePrice = consultant1.getServicePrice();
        //用户扣去对应服务费用
        HashMap<String,Object> map = new HashMap<>();
        map.put("servicePrice",servicePrice);
        map.put("id",query.getId());
        int i2  = userMapper.costMoney(map);

        //插入account_money表
        AccountMoney accountMoney = new AccountMoney();
        accountMoney.setMoney(servicePrice);
        accountMoney.setRevenueExpense(1);//0收入/1支出
        accountMoney.setRelationship(consultant1.getName() + "(咨询师)");
        accountMoney.setMatterId(2);//2在线考试
        accountMoney.setUId(query.getId());
        accountMoney.setCId(consultant1.getId());
        accountMoney.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(System.currentTimeMillis())));
        int i4 = accountMoneyMapper.insert(accountMoney);

        return Result.updateResp(i4,"预约添加成功","预约添加失败","");
    }

    @Override
    public Result showOrder(String username, int pageNo) {
        //通过username查询userId
        User user = new User();
        user.setUsername(username);
        User query = userMapper.query(user);
        Map<String,Object> map = new HashMap<>();
        map.put("uid",query.getId());
        map.put("limit",(pageNo - 1) * 5);
        map.put("offset",5);
        List<OrderListVo> list = subscribeMapper.queryForFront(map);
        list.forEach(System.out::println);
        Consultant query1 = null;
        Evaluate evaluateQuery = null;
        for (OrderListVo orderListVo : list) {
            Integer managerId = orderListVo.getManagerId();
            System.out.println(managerId+"   aaaaa");
            query1 = new Consultant();
            query1.setManagerId(managerId);
            Consultant consultant = new Consultant();
            consultant.setManagerId(managerId);
            Consultant consultant1 = consultantMapper.query2(consultant);
            System.out.println(consultant1  + "   11111");
            orderListVo.setCost(consultant1.getServicePrice());
            orderListVo.setConsName(consultant1.getName());
            //通过预约订单id获取评论
            evaluateQuery = new Evaluate();
            evaluateQuery.setSubId(orderListVo.getOrderId());
            Evaluate evaluate = evaluateMapper.query(evaluateQuery);
            orderListVo.setEvaluate(evaluate.getEvaluateInfo());
        }
        Page<OrderListVo> page = new Page();
        page.setPageNo(pageNo);
        page.setLimit((pageNo - 1) * 5);
        page.setOffset(5);
        page.setList(list);
        page.setTotalCount(subscribeMapper.queryTotalCountFront(map));
        System.out.println(page.getTotalCount());
        int totalCount = page.getTotalCount();
        page.setTotalPageCount(totalCount % 5 == 0 ? totalCount / 5 : totalCount / 5 + 1);
        if (page.getTotalPageCount() == 0) {
            page.setCurrentPage(0);
        }

        list.forEach(System.out::println);
        return new Result(0,"数据获取成功",page);
    }

    @Override
    public Result updateStatus(int id) {

        //通过subscribeId修改预约状态
        int i = subscribeMapper.update(id);

        return Result.updateResp(i,"状态修改成功","状态修改失败",null);
    }

    @Override
    public Result updateStatusForDiagnosis(int id, String answer) {
        //通过id 修改预约的状态（从已确认修改为已诊断），添加诊断答复，添加诊断时间
        Subscribe subscribe = new Subscribe();
        System.out.println(subscribe);
        subscribe.setId(id);
        subscribe.setAnswer(answer);
        subscribe.setSubStatus(4);
        subscribe.setAnswerTime(
                new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm:ss").format(
                        new Date(System.currentTimeMillis())));
        int i = subscribeMapper.updateForDiagnosis(subscribe);
        return Result.updateResp(i,"诊断成功","诊断失败",null);
    }

    @Override
    public Result getConsInfo(String consName) {
        Consultant consultant = new Consultant();
        consultant.setName(consName);
        ConsultantFrontVo consultant1 = consultantMapper.query3(consultant);
        List<ConsultantFieldVo> query = consultantFieldMapper.query(consultant1.getId());
        consultant1.setConsultantFieldVos(query);
        int i = consultant1 == null ? 0 : 1;
        return Result.updateResp(i,"获取咨询师数据成功","获取咨询师数据失败",consultant1);
    }

    @Override
    public Result evaluate(String orderId, String evaluate) {

        //表需要修改的是：评价，评价时间，预约状态
        //修改evaluate表
        Evaluate evaluate1 = new Evaluate();
        evaluate1.setEvaluateTime(new SimpleDateFormat(
                "yyyy-MM-dd hh:mm:ss").format(
                new Date(System.currentTimeMillis())));
        evaluate1.setSubId(orderId);
        evaluate1.setEvaluateInfo(evaluate);
        int i = evaluateMapper.update(evaluate1);

        //修改预约表中的预约状态(已评价 5)

        int i1 = subscribeMapper.update2(orderId);

        return Result.updateResp(i1,"评论成功","评论失败",null);
    }

    @Override
    public Result subscribeInfoForOne(int id) {

        OrderListVo orderListVo = subscribeMapper.queryForBack(id);
        System.out.println(orderListVo);
        // managerId=2 : cost=null consName=null,orderId=1661783277777:evaluate=null
        Consultant consultant = new Consultant();
        consultant.setManagerId(orderListVo.getManagerId());
        Consultant consultant1 = consultantMapper.query2(consultant);

        orderListVo.setCost(consultant1.getServicePrice());
        orderListVo.setConsName(consultant1.getName());

        Evaluate evaluate = new Evaluate();
        evaluate.setSubId(orderListVo.getOrderId());
        Evaluate query = evaluateMapper.query(evaluate);

        orderListVo.setEvaluate(query.getEvaluateInfo());

        int i = orderListVo == null ?0:1;

        return Result.updateResp(i,"数据获取成功","数据获取失败",orderListVo);
    }

    @Override
    public Result haveMoney(String username, int consId) {
        User user = new User();
        user.setUsername(username);
        User query = userMapper.query(user);
        Integer balance = query.getBalance();

        int servicePrice = consultantMapper.queryServicePrice(consId);

        if (balance < servicePrice){

            return new Result(-1,"用户余额不足，不能预约咨询师，请到我的账户进行充值。","");
        }
        return new Result(0,"用户余额足够","");
    }

    @Override
    public Result haveMoneyForOnlineExam(String username) {
        Configure configure = new Configure();
        configure.setKeyp("exam_cost");
        Configure configure1 = configureMapper.queryForOne(configure);


        User user = new User();
        user.setUsername(username);
        System.out.println(username);
        User query = userMapper.query(user);
        if (query.getBalance() >= Integer.parseInt(configure1.getValue())){
            return new Result(0,"用户余额足够！","");
        }
        return new Result(-1,"用户余额不足，请充值！","");
    }
}
